// -----------------------------------------------------------------------
//  <copyright file="UserLoggedInDomainEvent.cs" company="LiuliuSoft">
//      Copyright (c) 2022-2025 DaprPlus. All rights reserved.
//  </copyright>
//  <site>https://dapr.plus</site>
//  <last-editor>郭明锋</last-editor>
//  <last-date>2025/1/14 17:06</last-date>
// -----------------------------------------------------------------------

using DaprPlus.AspNetCore.Extensions;
using DaprPlus.Domain.Events;
using DaprPlus.Identity.Domain.Entities;

using DaprPlus.Identity.Application.Identity.Users.Commands;

using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;

namespace DaprPlus.Identity.Application.Identity.Users.Events;

public record UserLoggedInDomainEvent(LoginType LoginType, string Account, bool IsRemember, User User)
    : DomainEvent
{ }

public class CreateLoginLogHandler(IServiceProvider provider)
    : DomainEventHandlerBase<UserLoggedInDomainEvent>(provider)
{
    private readonly IServiceProvider _provider = provider;

    /// <summary>
    /// 重写以实现领域事件处理逻辑
    /// </summary>
    /// <param name="event">领域事件</param>
    /// <param name="token"></param>
    /// <returns></returns>
    protected override async Task OnHandle(UserLoggedInDomainEvent @event, CancellationToken token)
    {
        var accessor = _provider.GetRequiredService<IHttpContextAccessor>();
        var httpContext = accessor.HttpContext!;
        var ip = httpContext.GetClientIp();
        var userAgent = httpContext.Request.Headers.UserAgent.FirstOrDefault();
        @event.User.CreateLoginLog(ip, userAgent, $"Login type: {@event.LoginType}");

        var repository = _provider.GetRepository<User>();
        await repository.UpdateAsync(@event.User, token);
    }
}
